/**
 * Copyright 2012 SVC Delivery Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package sc.client;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import com.google.gwt.core.client.GWT;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteHandler;
import com.google.gwt.user.client.ui.FormPanel.SubmitEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitHandler;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.SubmitButton;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

public class LoginWidget extends Composite {
	private FormPanel formPanel;
	/**
	 * Create a remote service proxy to talk to the server-side Greeting service.
	 */
	private final LoginServiceAsync	loginService	= GWT.create( LoginService.class );

	public LoginWidget() {
		this(null);
	}

	public LoginWidget(final DialogBox dialog) {
		final boolean useAjax = dialog != null;
		formPanel = new FormPanel("_self");
		initWidget(formPanel);
		VerticalPanel vpanel = new VerticalPanel();
		HorizontalPanel hpanel = new HorizontalPanel();
		final TextBox userName = new TextBox();
		final TextBox password = new PasswordTextBox();

		formPanel.setAction("j_security_check");
		formPanel.setMethod(FormPanel.METHOD_POST);
		hpanel.add(new Label("User name:"));
		hpanel.add(userName);
		userName.setName("j_username");
		vpanel.add(hpanel);

		hpanel = new HorizontalPanel();
		hpanel.add(new Label("Password:"));
		hpanel.add(password);
		password.setName("j_password");
		vpanel.add(hpanel);

		SubmitButton login = new SubmitButton("Login");
		vpanel.add(login);

		formPanel.addSubmitHandler(new SubmitHandler() {

			@Override
			public void onSubmit(SubmitEvent event) {
				if (useAjax) {
					event.cancel();
					String url = formPanel.getAction();
					// Submit login request.
					RequestBuilder rb = new RequestBuilder(RequestBuilder.POST,
							url);
					rb.setHeader("Content-Type",
							"application/x-www-form-urlencoded");
					Map<String, String> requestMap = new HashMap<String, String>();
					requestMap.put("j_username", userName.getText());
					requestMap.put("j_password", password.getText());
					String requestData = buildQueryString(requestMap);
					rb.setRequestData(requestData);
					rb.setCallback(new RequestCallback() {

						@Override
						public void onResponseReceived(Request request,
								Response response) {
							if (dialog != null) {
								dialog.hide();
							}
						}

						@Override
						public void onError(Request request, Throwable exception) {
							// TODO Add error message.
						}
					});
					try {
						rb.send();
					} catch (RequestException e) {
						// TODO Add error message.
					}
				}
			}

			public String buildQueryString(Map<String, String> queryEntries) {
				StringBuffer sb = new StringBuffer();

				for (Entry<String, String> queryEntry : queryEntries.entrySet()) {

					if (sb.length() != 0) {
						sb.append("&");
					}

					// encode the characters in the name
					String encodedName = URL.encodeQueryString(queryEntry
							.getKey());
					sb.append(encodedName);

					sb.append("=");

					// encode the characters in the value
					String encodedValue = URL.encodeQueryString(queryEntry
							.getValue());
					sb.append(encodedValue);
				}

				return sb.toString();
			}
		});

		formPanel.add(vpanel);
	}

	public void addSubmitHandler(SubmitCompleteHandler handler) {
		formPanel.addSubmitCompleteHandler(handler);
	}
}
